package javabasics.nio;


import java.io.*;
import java.nio.channels.FileChannel;

/**
 * 测试 NIO 性能
 *
 * @Author suxiaoxiao
 * @Date 2019/6/13 23:53
 * @Version 1.0
 */
public class ByteBuffer {

    /**
     * ByteBuffer 写耗时: 114 ms
     * ByteBuffer 读耗时：80 ms
     * @param args
     */
    public static void main(String[] args) {
        // 写入数据大小
        int numOfInts = 4000000;

//        Long startTime = System.currentTimeMillis();
//        ByteBufferWriteFile(numOfInts);
//        System.out.println("ByteBuffer 写耗时：" + (System.currentTimeMillis() - startTime));

        Long startTime = System.currentTimeMillis();
        ByteBufferReadFile(numOfInts);
        System.out.println("ByteBuffer 读耗时：" + (System.currentTimeMillis() - startTime));

    }

    public static void ByteBufferWriteFile(int numOfInts) {
        try {
            FileOutputStream fout = new FileOutputStream(new File("d:\\temp_buffer.tmp"));
            // 通道
            FileChannel fc = fout.getChannel();
            // 缓冲区
            java.nio.ByteBuffer byteBuffer = java.nio.ByteBuffer.allocate(numOfInts * 4);
            for (int i = 0; i < numOfInts; i++) {
                byteBuffer.put(int2byte(i));
            }
            // 读写模式切换
            byteBuffer.flip();
            // 写入
            fc.write(byteBuffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void ByteBufferReadFile(int numOfInts) {
        try {
            FileInputStream fin = new FileInputStream(new File("d:\\temp_buffer.tmp"));
            FileChannel fileChannel = fin.getChannel();
            java.nio.ByteBuffer byteBuffer = java.nio.ByteBuffer.allocate(numOfInts * 4);
            fileChannel.read(byteBuffer);
            fileChannel.close();
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                byte2int(byteBuffer.get(), byteBuffer.get(), byteBuffer.get(), byteBuffer.get());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] int2byte(int res) {
        byte[] targets = new byte[4];
        targets[3] = (byte) (res & 0xff);
        targets[2] = (byte) ((res >> 8) & 0xff);
        targets[1] = (byte) ((res >> 16) & 0xff);
        targets[0] = (byte) (res >>> 24);
        return targets;
    }

    public static int byte2int(byte b1, byte b2, byte b3, byte b4) {
        return ((b1 & 0xff) << 24 | ((b2 & 0xff) << 16) | (b3 & 0xff) << 8 | (b4 & 0xff));
    }

}
